package com.baseweb.webadmin.controller.web;

import com.baseweb.webadmin.core.model.bvo.ByUserBizProductBvo;
import com.baseweb.webadmin.core.model.pojo.ByOpenCity;
import com.baseweb.webadmin.core.model.pojo.ByUserBizProduct;
import com.baseweb.webadmin.core.model.pojo.ByUserOrder;
import com.baseweb.webadmin.core.model.pojo.User;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import com.google.gson.Gson;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zx on 2017/7/15.
 */
@Controller
@RequestMapping("/htmlWeb/")
public class ProductManageController {

    private static final Logger logger = LoggerFactory.getLogger(ProductManageController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private UserOrderService userOrderService;

    @RequestMapping(value = "/getProducts")
    @ResponseBody
    public ResultPage getProducts(@RequestParam(value = "cnName") String cnName,
                                  @RequestParam(value = "userMobile") String userMobile,
                                  @RequestParam(value = "userChannel") String userChannel,
                                  @RequestParam(value = "keyword") String keyword,
                                  @RequestParam(value = "auditType") Integer auditType,
                                  @RequestParam(value = "status") Integer status,
                                  @RequestParam(value = "startTime") String startTime,
                                  @RequestParam(value = "endTime") String endTime,
                                  @RequestParam(value = "province") String province,
                                  @RequestParam(value = "city") String city,
                                  @RequestParam(value = "county") String county,
                                  Model model, RequestPage requestPage, HttpServletRequest request) {

        Integer userId = Integer.valueOf(request.getSession().getAttribute("login_id").toString());
        String _county = "", _city = "", _province = "";
        if (userId != 1) {
            // 获取当前登录用户所对应的开通城市
            List<ByOpenCity> byOpenAreaList = userService.findOpenCityByUserId(userId);

            if (city != null && !"".equals(city)) {
                if (!byOpenAreaList.isEmpty()) {
                    for (int i = 0, size = byOpenAreaList.size(); i < size; i++) {
                        if (byOpenAreaList.get(i).getCity().equals(city)) {
                            _city = city;
                            break;
                        }
                        if (_city.equals("") && i == byOpenAreaList.size() - 1) {
                            _city = "-1";
                        }
                    }
                } else {
                    _city = "-1";
                }
            } else if (province != null && !"".equals(province)) {
                if (!byOpenAreaList.isEmpty()) {
                    for (int i = 0, size = byOpenAreaList.size(); i < size; i++) {
                        if (byOpenAreaList.get(i).getProvince().equals(province)) {
                            _province = province;
                            break;
                        }
                        if (_province.equals("") && i == byOpenAreaList.size() - 1) {
                            _province = "-1";
                        }
                    }
                } else {
                    _province = "-1";
                }
            }
            if (county != null && !county.equals("")) {
                if (!byOpenAreaList.isEmpty()) {
                    for (int i = 0, size = byOpenAreaList.size(); i < size; i++) {
                        if (byOpenAreaList.get(i).getArea().equals(county)) {
                            _county = "'" + county + "'";
                            break;
                        }
                        if (_county.equals("") && i == byOpenAreaList.size() - 1) {
                            _county = "-1";
                        }
                    }
                } else {
                    _county = "-1";
                }
            } else {
                for (int i = 0, size = byOpenAreaList.size(); i < size; i++) {
                    _county += ",'" + byOpenAreaList.get(i).getArea() + "'";
                }
                _county = _county.substring(1);
            }
        } else {
            _province = province;
            _city = city;
            _county = (county != null && !"".equals(county)) ? "'" + county + "'" : "";
        }

        List<ByUserBizProductBvo> productBvos = userService.selectProductVoListByPage(null, cnName, userMobile, userChannel, keyword, auditType, status, startTime, endTime, _province, _city, _county,
                (requestPage.getCurPage()-1)*requestPage.getPageSize(), requestPage.getPageSize());
        int total = userService.selectProductListCount(cnName, userMobile, userChannel, keyword, auditType, status, startTime, endTime, _province, _city, _county);
        return new ResultPage<>(total, requestPage.getPageSize(), requestPage.getCurPage(), productBvos);
    }

    /**查询报价信息列表
     *
     * @param request
     * @param requestPage
     * @return
     */
    @RequestMapping(value = "/getProductList")
    @ResponseBody
    public ResultPage getOrderDetailList(@RequestParam(value = "merId", required = false) Integer merId,
                                         @RequestParam(value = "name", required = false) String name,
                                         @RequestParam(value = "productType", required = false) Integer productType,
                                         @RequestParam(value = "status", defaultValue = "0") Integer status,
                                        HttpServletRequest request,RequestPage requestPage) {
        List<ByUserBizProduct> products = new ArrayList<>();
        int total = 0;
        if (merId == null || merId == 0) {
            products = userService.selectProductListByPage(null, productType, null, (requestPage.getCurPage() - 1) * requestPage.getPageSize(),
                    requestPage.getPageSize(), null, null, null, name, status);
            total = userService.selectProductListCount(null, productType, null, null, null, null, name, status);
        } else {
            products = userService.selectProductListByPage(merId, productType, null, (requestPage.getCurPage() - 1) * requestPage.getPageSize(),
                    requestPage.getPageSize(), null, null, null, name, status);
            total = userService.selectProductListCount(merId, productType, null, null, null, null, name, status);
        }

        return new ResultPage<>(total, requestPage.getPageSize(), requestPage.getCurPage(), products);
    }

    /**
     * 根据ID获取商品详细信息
     * @param id 商品ID
     * @return 商品详细信息
     */
    @RequestMapping(value = "/getProductById", produces = "text/json; charset=UTF-8")
    @ResponseBody
    public String getProductById(@RequestParam(value = "id") Integer id) {
        ByUserBizProduct product = userService.findBizProduct(id);
        String result = "";
        if (product != null) {
            Gson gson = new Gson();
            result = gson.toJson(product);
        } else {
            result = "";
        }
        return result;
    }

    /**
     * 新增报价信息
     * @param name 服务名
     * @param descn 描述
     * @param original_price 原价
     * @param current_price 现价
     * @param coins
     * @param unit 单位
     * @param status 状态（1-正常；-1-删除）
     * @param deposit
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/addProduct")
    @ResponseBody
    public String addProduct(@RequestParam(value = "id",required = false) Integer id,
                             @RequestParam(value = "name",required = false) String name,
                             @RequestParam(value = "descn",required = false) String descn,
                             @RequestParam(value = "original_price",required = false) String original_price,
                             @RequestParam(value = "current_price",required = false) String current_price,
                             @RequestParam(value = "coins",defaultValue = "0") Integer coins,
                             @RequestParam(value = "unit",required = false) String unit,
                             @RequestParam(value = "status",defaultValue = "-1") Integer status,
                             @RequestParam(value = "deposit",required = false) String deposit,
                             HttpServletRequest request,
                             Model model) {
        String retMsg = "";
        try{
            ByUserBizProduct byUserBizProduct = null;
            byUserBizProduct = new ByUserBizProduct();
            User user = null;
            if (id == null || id == 0) {
                Integer userId = Integer.valueOf(request.getSession().getAttribute("login_id").toString());
                user = userService.selectUserById(userId);
                byUserBizProduct.setUserId(userId);
                byUserBizProduct.setChannelId(user.getBizWorkType());
                byUserBizProduct.setCreateTime(new DateTime());
            } else {
                byUserBizProduct = userService.findBizProduct(id);
            }

            byUserBizProduct.setName(name);
            byUserBizProduct.setDescn(descn);
            byUserBizProduct.setStatus(status);
            byUserBizProduct.setCurrentPrice(ObjectFormatter.str2BigDecimal(current_price));
            byUserBizProduct.setCoins(coins);
            byUserBizProduct.setDeposit(ObjectFormatter.str2BigDecimal(deposit));
            byUserBizProduct.setUnit(unit);
            byUserBizProduct.setUpdateTime(new DateTime());
            byUserBizProduct.setProductType(0);
            byUserBizProduct.setAuditCount(byUserBizProduct.getAuditCount() != null ? (byUserBizProduct.getAuditCount() + 1) : 1);
            userService.insertBizProduct(byUserBizProduct);

            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }

        Gson gson = new Gson();
        String result = gson.toJson(model);
        return result;
    }

    /**
     * 根据商品ID删除商品信息
     * @param id 商品ID
     * @param status 商品状态   1 - 上架；2 - 删除；-1 - 下架
     * @param model 模型
     * @return 是否成功
     */
    @RequestMapping(value = "/updateProductStatus")
    @ResponseBody
    public String updateProductStatus(@RequestParam(value = "id") Integer id,
                                     @RequestParam(value = "status") Integer status,
                                     HttpServletRequest request,
                                     Model model) {
        try {
            ByUserBizProduct byUserBizProduct = userService.findBizProduct(id);
            byUserBizProduct.setStatus(status);
            if (status == 2) { // 商品删除
                List<ByUserOrder> userOrders = userOrderService.selectOrderByProductId(id); // 根据产品ID获取订单信息
                int deCount = 0;
                if (userOrders != null && !userOrders.isEmpty()) {
                    for (ByUserOrder order : userOrders) {
                        if (order.getStatus() != 6 && order.getStatus() != 7) {
                            deCount++;
                        }
                    }
                }
                if (deCount > 0) {
                    model.addAttribute("isDelete", false);
                    model.addAttribute("isSuccess", false);
                } else {
                    userService.insertBizProduct(byUserBizProduct);
                    model.addAttribute("isSuccess", true);
                }
            } else {
                userService.insertBizProduct(byUserBizProduct);
                model.addAttribute("isSuccess", true);
            }
            // 修改user表中biz_price价格字段，以便排序 ***** start *****
            if (status == 1) { // 上架时更新最小价格
                Integer userId = Integer.valueOf(request.getSession().getAttribute("login_id").toString());
                User user = userService.selectUserById(userId);
                List<ByUserBizProduct> products = userService.selectProductListByPage(userId, null, null, 0, 99, null, null, null, null, 1);
                if (products != null && products.size() > 0) {
                    BigDecimal price = user.getBizPrice();
                    BigDecimal mix = null;
                    for (ByUserBizProduct product : products) {
                        BigDecimal cur_price = product.getCurrentPrice();
                        if (mix == null || cur_price.compareTo(mix) == -1) {
                            mix = cur_price;
                        }
                    }
                    if (mix != null && (price.compareTo(new BigDecimal(0)) == 0 || mix.compareTo(price) == -1)) {
                        user.setBizPrice(mix);
                        userService.updateByPrimaryKey(user);
                    }
                }
            }
            // 修改user表中biz_price价格字段，以便排序 ***** end *****
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("isSuccess", false);
        }

        Gson gson = new Gson();
        String result = gson.toJson(model);
        return result;
    }

    /**
     * 根据商品ID更改商品审核状态信息
     * @param id 商品ID
     * @param proType 商品审核状态   0 - 待审核；1 - 审核通过；2 - 审核不通过
     * @param model 模型
     * @return 是否成功
     */
    @RequestMapping(value = "/updateProductType")
    @ResponseBody
    public String updateProductType(@RequestParam(value = "id") Integer id,
                                      @RequestParam(value = "proType") Integer proType,
                                      Model model) {
        try {
            ByUserBizProduct byUserBizProduct = userService.findBizProduct(id);
            byUserBizProduct.setProductType(proType);
            if (proType == 2) { // 当审核不通过时，商品自动下架
                byUserBizProduct.setStatus(-1);
            }
            userService.insertBizProduct(byUserBizProduct);
            model.addAttribute("isSuccess", true);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("isSuccess", false);
        }

        Gson gson = new Gson();
        String result = gson.toJson(model);
        return result;
    }
}
